<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/8/3
 * Time: 13:51
 */

namespace app\modules\mch\controllers;


//use app\models\LiveSetting;
use app\models\LiveActor;
use app\models\LiveSetting;
use app\models\LiveIndex;
use app\models\LiveStream;
use app\models\Store;

use app\modules\mch\models\AgentListForm;
use app\modules\mch\models\LiveSettingForm;
use app\modules\mch\models\LiveIndexForm;
use app\modules\mch\models\LiveStreamForm;
use app\modules\mch\models\GoodsForm;
use app\modules\mch\models\LiveActorForm;

use app\models\Cat;
use app\models\Goods;
use app\models\Agent;


use yii\data\Pagination;



class LiveController extends Controller
{
    public function token($org_name,$app_name,$client_id,$client_secret){
        $url = "https://a1.easemob.com/".$org_name."/".$app_name."/token";
        $post_data = array ("grant_type" => "client_credentials","client_id" => $client_id,"client_secret"=>$client_secret);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $output = curl_exec($ch);
        $err = curl_error($ch);
//        var_dump($err);
        $data = json_decode($output);
//        var_dump($data);
//        exit();
        return  $data->access_token;
        curl_close($ch);

    }
    //设置直播流
    public function stream($push_stream,$pull_stream,$token){
        $acid = $_COOKIE['70d4___uniacid'];
        $res = Store::find()->where(['acid'=>$acid])->one();
        $wechat_app_id = $res['wechat_app_id'];
        $result = LiveSetting::find()->where(['wechat_app_id'=>$wechat_app_id])->one();
        $url = "https://a1.easemob.com/".$result['org_name']."/".$result['app_name']."/liverooms/stream_url";
        $head=array();
        $head[]='Authorization: Bearer '.$token;
        $post_data = array("pc_pull"=>$pull_stream,"pc_push"=>$push_stream,"mobile_pull"=>$pull_stream,"mobile_push"=>$push_stream);
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$head);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

        $output = curl_exec($ch);
        $data = json_decode($output);
        $err = curl_error($ch);
        return $data;

    }

    public function imuser($user_name , $password,$org_name,$app_name){
        $url = "https://a1.easemob.com/".$org_name."/".$app_name."/users";
        $post_data = array("username"=>"test","password"=>'test');
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
//    curl_setopt($ch, CURLOPT_HTTPHEADER,$head);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

        $output = curl_exec($ch);

        $err = curl_error($ch);
        $datainfo['out']=$output;
    }
    public function actor($user_name , $password,$org_name,$app_name,$token){
//        imuser($user_name , $password,$org_name,$app_name);
        $url = "https://a1.easemob.com/".$org_name."/".$app_name."/chatrooms/super_admin";
        $post_data = array("superadmin"=>$user_name);
        $head=array();
        $head[] ='Authorization: Bearer '.$token;
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$head);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

        $output = curl_exec($ch);

        $err = curl_error($ch);

        return json_decode($output);
    }

    public function actionIndex()
    {

//        $acid = $_COOKIE['70d4___uniacid'];
//        $res = Store::find()->where(['acid'=>$acid])->one();
//        $wechat_app_id = $res['wechat_app_id'];
        $wechat_app_id = \Yii::$app->request->get('store_id');
        if(\Yii::$app->request->isPost) {
            $form = new LiveIndexForm();
            $form->wechat_app_id = $wechat_app_id;
            $data = \Yii::$app->request->post();
            $form->status=$data['status'];
            $form->actor_imgurl = $data['actor_imgurl'];
            $form->number = $data['number'];
            $form->total = $data['total'];
            $form->room_name = $data['room_name'];
            $form->name = $data['name'];
            $form->begin_time = $data['begin_time'];
            $form->end_time = $data['end_time'];
            return $this->renderJson($form->save());

        }else {
            $datainfo = LiveSetting::find()->where(['wechat_app_id'=>$wechat_app_id])->one();
            return $this->render('index', [
            'type' => $datainfo['status'],
            'actor_imgurl'=>$datainfo['actor_imgurl'],
                'number'=>$datainfo['number'],
                'total'=>$datainfo['total'],
                'room_name'=>$datainfo['room_name'],
                'name'=>$datainfo['name'],
                'begin_time'=>$datainfo['begin_time'],
                'end_time'=>$datainfo['end_time'],
            ]);
        }
    }
    public function actionSetting()
    {
        //获取小程序ID
//        $acid = $_COOKIE['70d4___uniacid'];
//        $res = Store::find()->where(['acid'=>$acid])->one();
        $wechat_app_id = \yii::$app->request->get('store_id');
//        echo $wechat_app_id;
        if(\Yii::$app->request->isPost){
            $data = \Yii::$app->request->post();
//            var_dump($data);

            $form = new LiveSettingForm();
            $form->app_key  = $data['app_key'];
            $form->org_name = $data['org_name'];
            $form->app_name = $data['app_name'];
            $form->client_id = $data['client_id'];
            $form->client_secret = $data['client_secret'];
            $form->wechat_app_id = $wechat_app_id;
            $form->is_delete = 0;
            $form->access_token = $this->token($data['org_name'],$data['app_name'],$data['client_id'],$data['client_secret']);
            $form->createtime = date('Y-m-d H:i:s',time());
//            var_dump($form->access_token);
            if($form->access_token==''){
                $data=array('code'=>1,'msg'=>'请检查各项内容是否与环信一致','store_id'=>$wechat_app_id);
            }else{
                $data = $form->save();
            }
            return $this->renderJson($data);
        }else {
            $datainfo = LiveSetting::find()->where(['wechat_app_id'=>$wechat_app_id])->one();
            $data = array('store_id'=>$wechat_app_id);
            return $this->render('setting', [
            'datainfo'=>$datainfo,
                'data'=>$data,
            ]);
        }

    }
    //添加主播
    public function actionActor(){
//        $acid = $_COOKIE['70d4___uniacid'];
//        $res = Store::find()->where(['acid'=>$acid])->one();
        $wechat_app_id = \Yii::$app->request->get('store_id');
        if(\Yii::$app->request->isPost){
            $datas = \Yii::$app->request->post();
            $form = new LiveActorForm();
            $form->wechat_app_id = $wechat_app_id;
            $form->actor_name = $datas['actor_name'];
//            var_dump($datas);
            $form->actor_secret = '123456';
            $res= Agent::find()->where(['store_id'=>$wechat_app_id])->select('pingtai_id')->asArray()->all();
            $pingtai_id = $res[0]['pingtai_id'];
            $result = LiveSetting::find()->where(['wechat_app_id'=>$pingtai_id])->one();
            if($result['access_token']==''){
                $data = array('code'=>1,'msg'=>'请先填写直播设置');
            }else {
                $data = $form->save();
                if ($data['code'] == 0) {
                    $info = $this->actor($datas['actor_name'],$datas['actor_secret'],$result['org_name'],$result['app_name'],$result['access_token']);
                    if ($info->error != '') {
                        $token = $this->token($result['org_name'], $result['app_name'], $result['client_id'], $result['client_secret']);
                        LiveSetting::updateAll(['access_token' => $token], ['wechat_app_id' => $wechat_app_id]);
                        $info2 = $this->actor($datas['actor_name'],$datas['actor_secret'],$result['org_name'],$result['app_name'],$token);
//                            var_dump($info2);
                        if ($info2->error == '') {
                            $data = array('code' => 0, 'msg' => '保存成功','store_id'=>$wechat_app_id);
                        }
                    }else{
                        $data = array('code' => 0, 'msg' => '保存成功','store_id'=>$wechat_app_id);
                    }
                }
            }
            return $this->renderJson($data);
        }else {
//            $datainfo = \Yii::$app->request->get('store_id');
            $data=array('store_id'=>$wechat_app_id);
            return $this->render('actor', [
                'datainfo'=>$data,
            ]);
        }
    }

    //添加推流、拉流地址
    function actionStream(){
//        $acid = $_COOKIE['70d4___uniacid'];
//        $res = Store::find()->where(['acid'=>$acid])->one();
//        $wechat_app_id = $res['wechat_app_id'];
        $wechat_app_id = \Yii::$app->request->get('store_id');

        if(\Yii::$app->request->isPost){

            $data_info = \Yii::$app->request->post();
            $form = new LiveStreamForm();
            $form->wechat_app_id = $wechat_app_id;
            $form->push_stream = $data_info['push_stream'];
            $form->pull_stream = $data_info['pull_stream'];
            //查询平台是否设置
//            $res= Agent::find()->where(['store_id'=>$wechat_app_id])->select('pingtai_id')->asArray()->all();
//            $pingtai_id = $res[0]['pingtai_id'];
            $result = LiveSetting::find()->where(['wechat_app_id'=>$wechat_app_id])->one();
            if($result['access_token']==''){
                $data = array('code'=>1,'msg'=>'请先填写直播设置');
            }else {
                $data = $form->save();
                if ($data['code'] == 0) {
                    $info = $this->stream($data_info['push_stream'], $data_info['pull_stream'], $result['access_token']);
                        if ($info->error != '') {
                            $token = $this->token($result['org_name'], $result['app_name'], $result['client_id'], $result['client_secret']);
                            LiveSetting::updateAll(['access_token' => $token], ['wechat_app_id' => $wechat_app_id]);
                            $info2 = $this->stream($data_info['push_stream'], $data_info['pull_stream'], $token);
//                            var_dump($info2);
                            if ($info2->error == '') {
                                $data = array('code' => 0, 'msg' => '保存成功','store_id'=>$wechat_app_id);
                            }
                        }else{
                            $data = array('code' => 0, 'msg' => '保存成功');
                        }
                    }
                }
            return $this->renderJson($data);

        }else {
            $datainfo = LiveStream::find()->where(['wechat_app_id'=>$wechat_app_id])->one();
            $data=array('store_id'=>$wechat_app_id);
            return $this->render('stream', [
                'datainfo'=>$datainfo,
                'data'=>$data,
            ]);
        }


    }


    public function actionGoods($keyword = null){
        $query = Goods::find()->alias('g')->where(['g.store_id' => $this->store->id, 'g.is_delete' => 0]);
        $query->leftJoin(['c' => Cat::tableName()], 'c.id=g.cat_id');
        $cat_query = clone $query;
        if (trim($keyword)) {
            $query->andWhere([
                'OR',
                ['LIKE', 'g.name', $keyword],
                ['LIKE', 'c.name', $keyword],
            ]);
        }
        if (isset($_GET['cat'])) {
            $cat = trim($_GET['cat']);
            $query->andWhere(['like', 'c.name', $cat]);
        }
        $cat_list = $cat_query->groupBy('g.cat_id')->orderBy(['g.cat_id' => SORT_ASC])->select(['c.name'])->asArray()->column();
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count,]);
        $list = $query->orderBy('g.sort ASC,g.addtime DESC')->limit($pagination->limit)->offset($pagination->offset)->all();

        return $this->render('goods', [
            'list' => $list,
            'pagination' => $pagination,
            'cat_list' => $cat_list
        ]);
}

    //添加进直播间
    public function actionGoodstolive($id=0 , $type='addtolive'){
//        echo $id,'...',$type;
//        exit();
        if($type=='addtolive') {
            $goods = Goods::findOne(['id' => $id, 'is_live' => 0, 'store_id' => $this->store->id]);
            if (!$goods) {
                $this->renderJson([
                    'code' => 1,
                    'msg' => '商品添加失败或已添加进直播间'
                ]);
            }else {
                $goods->is_live = 1;
            }
        }else{
            $goods = Goods::findOne(['id' => $id, 'is_live' => 1, 'store_id' => $this->store->id]);
            if (!$goods) {
                $this->renderJson([
                    'code' => 1,
                    'msg' => '商品从直播间删除失败或已从直播间删除'
                ]);
            }else {
                $goods->is_live = 0;
            }
        }

        if ($goods->save()) {
            $this->renderJson([

                'code' => 0,
                'msg' => '成功'
            ]);
        } else {
            foreach ($goods->errors as $errors) {
                $this->renderJson([
                    'code' => 1,
                    'msg' => $errors[0],
                ]);
            }
        }
    }
//批量处理
    public function actionBatch()
    {
        $get = \Yii::$app->request->get();
        $res = 0;
        $goods_group = $get['goods_group'];
//        var_dump($goods_group);
        $goods_id_group = [];
        foreach ($goods_group as $index => $value) {
            if ($get['type'] == 0) {
                if ($value['num'] != 0) {
                    array_push($goods_id_group, $value['id']);
                }
            } else {
                array_push($goods_id_group, $value['id']);
            }
        }

        $condition = ['and', ['in', 'id', $goods_id_group], ['store_id' => $this->store->id]];
        if ($get['type'] == 0) { //批量添加进直播间
            $res = Goods::updateAll(['is_live' => 1], $condition);
        } elseif ($get['type'] == 1) {//批量退出直播间
            $res = Goods::updateAll(['is_live' => 0], $condition);
        }
        if ($res > 0) {
            $this->renderJson([
                'code' => 0,
                'msg' => 'success'
            ]);
        } else {
            $this->renderJson([
                'code' => 1,
                'msg' => 'fail'
            ]);
        }
    }
    public function actionAgent()
    {
        $form = new AgentListForm();
        $form->attributes = \Yii::$app->request->get();
        $arr = $form->list_search();
        return $this->render('agent',[
            'list'=>$arr['list'],
            'pagination'=>$arr['p'],
            'row_count'=>$arr['row_count']
        ]);
    }



   }